#include "stdafx.h"
#include "QConnectionManager.h"


QConnectionManager::QConnectionManager()
{

}

QConnectionManager::~QConnectionManager()
{

}

QConnectionManager& QConnectionManager::GetInstance()
{
    static QConnectionManager instance;
    return instance;
}

bool QConnectionManager::GetInfoByConnection(QTcpSocket* pSock, LoginInfo& info)
{
    if (pSock == nullptr)
    {
        return false;
    }

    info = m_ConnectionMap[pSock];

    return true;
}

void QConnectionManager::SetInfoByConnection(QTcpSocket* pSock, LoginInfo& info)
{
    m_ConnectionMap[pSock] = info;
}

QTcpSocket* QConnectionManager::GetSockByUserName(QString const& userName)
{
    for (auto iter = m_ConnectionMap.begin(); iter != m_ConnectionMap.end(); ++iter)
    {
        if (iter.value().userName == userName)
        {
            return iter.key();
        }
    }

    return nullptr;
}

void QConnectionManager::DeleteConnectionBySock(QTcpSocket* pSock)
{
    pSock->close();
    m_ConnectionMap.remove(pSock);
}

void QConnectionManager::DeleteConnectionByUserName(QString const& userName)
{
    for (auto iter = m_ConnectionMap.begin(); iter != m_ConnectionMap.end(); ++iter)
    {
        if (iter.value().userName == userName)
        {
            iter.key()->close();
            m_ConnectionMap.remove(iter.key());
        }
    }
}

QVector<LoginInfo> QConnectionManager::GetLoginInfoList()
{
    QVector<LoginInfo> res;

    for (auto item : m_ConnectionMap.values())
    {
        res.push_back(item);
    }

    return res;
}

void QConnectionManager::OnSocketClosed()
{
    QTcpSocket* pSock = (QTcpSocket*)sender();
    if (pSock == nullptr)
    {
        return;
    }

    m_ConnectionMap.remove(pSock);
    pSock->deleteLater();
}

